$(function() {

    const btnPublish = $('.article-edit .publish')
    const btnDel = $('.article-edit .del')
    const title = $('.article-edit_title input')
    const category = $('.article-edit_category input')


    // 文章编辑
    const E = window.wangEditor

    const editor = new E("#edit");

    editor.config.excludeMenus = [
        'video'
    ]

    const save = () => {
        
        title.val(localStorage['_title_'])
        category.val(localStorage['_category_'])

        editor.config.onchange = function() {
            localStorage['_editor_'] = editor.txt.html()
        }
        title.on('change', () => {
            localStorage['_title_'] = title.val()
        })
        category.on('change', () => {
            localStorage['_category_'] = category.val()
        })
    }
    const clearStore = () => {
        delete localStorage['_category_']
        delete localStorage['_title_']
        delete localStorage['_editor_']
    }
    save()

    editor.create();
    editor.cmd.do('insertHTML', localStorage['_editor_'])

    const query = queryString(location.href)
    
    if (query.id) {
        btnDel.attr('disabled', false)
        btnDel.on('click', () => {
            // query.id 删除当前文章
            // 跳转回首页
            if (window.confirm('是否真的要删除') && query.id) {
                $.ajax({
                    url: `/article?id=${query.id}`,
                    method: 'delete',
                    success: function() {
                        // 删除成功, 刷新页面
                        window.location = '/'
                        clearStore()
                    }
                })
            }
        })
    }


    btnPublish.on('click', () => {
        let data = {
            title: title.val(),
            category: category.val(),
            html_body: editor.txt.html(),
            text_body: editor.txt.text(),
            id: query.id,
        }
        let method = 'PUT' // POST
        console.log(data)
        if (query.id) {
            method = 'POST'
        }
        $.ajax({
            url: '/article',
            method,
            data,
            success: function() {
                // 修改/新增完毕

                // 清除编辑器缓存
                clearStore()

                // 跳转回首页
                window.location = '/'
            },
        })
    })


    $('.article-item-edit .delete').on('click', function() {
        const { id } = this.dataset
        if (window.confirm('是否真的要删除') && id) {
            $.ajax({
                url: `/article?id=${id}`,
                method: 'delete',
                success: function() {
                    // 删除成功, 刷新页面
                    window.location.reload()
                }
            })
        }
    })

})